﻿// This software is the confidential and proprietary information of NetBay.
// Such confidential information should not be disclosed.
// NetBay copyright(c) 2012

#region

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Web;
using NetBay.Core.BusinessEntities.Historic;
using Rio.Applications.Web.Services;
using Rio.Doc.Business.Repository;
using Rio.Doc.Business.Repository.Translator;
using Rio.Doc.DataAccess;

#endregion

namespace Rio.Applications.Web.RioServices
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class RioService : IRioService
    {
        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="RioService" /> class.
        /// </summary>
        public RioService()
        {
            DomainService = new BusinessEntitiesDomainService();
        }

        #endregion

        #region Instance Properties

        /// <summary>
        /// Gets the authenticate user.
        /// </summary>
        /// <value>The authenticate user.</value>
        private NetBay.Core.BusinessEntities.User AuthenticatedUser { get; set; }

        /// <summary>
        /// Gets or sets the domain service.
        /// </summary>
        /// <value>The domain service.</value>
        private BusinessEntitiesDomainService DomainService { get; set; }

        #endregion

        #region Instance Methods

        /// <summary>
        /// Sets the actual context.
        /// </summary>
        private void SetContextState()
        {
            if (AuthenticatedUser == null)
            {
                throw new Exception("Unauthenticated User!");
            }
            if (HttpContext.Current.Session[ParameterSession.CurrentUser.szGetDescription()] == null)
            {
                HttpContext.Current.Session[ParameterSession.CurrentUser.szGetDescription()] = AuthenticatedUser;
            }
        }

        #endregion

        #region IRioService Members

        /// <summary>
        /// Adds the document to folder.
        /// </summary>
        /// <param name="OrganisationId">The organisation id.</param>
        /// <param name="FolderTypeId">The folder type id.</param>
        /// <param name="FolderId">The folder id.</param>
        /// <param name="DocumentsFullPath">The documents full path.</param>
        /// <param name="Item">The item.</param>
        /// <param name="Rank">The rank.</param>
        /// <param name="Author">The author.</param>
        /// <param name="Note">The note.</param>
        /// <param name="AddToFulltext">Add to fulltext.</param>
        /// <param name="MoveDocument">Documents moved to the folder.</param>
        /// <returns></returns>
        public bool AddDocumentsToFolder(long OrganisationId, long FolderTypeId, long FolderId,
                                         List<string> DocumentsFullPath, string Item, long Rank, string Author,
                                         string Note, bool AddToFulltext, bool MoveDocument)
        {
            NetBay.Core.Log.LogManager.Instance().LogDebug("(OrganisationId<" + OrganisationId.ToString() +
                                                           "> FolderTypeId<" + FolderTypeId + "> FolderId<" + FolderId +
                                                           "> DocumentsFullPath.count<" + DocumentsFullPath.Count +
                                                           "> Item<" + Item + "> Rank<" + Rank + "> Author<" + Author +
                                                           "> Note<" + Note + "> AddToFulltext<" +
                                                           AddToFulltext.ToString() + "> MoveDocument<" +
                                                           MoveDocument.ToString() + ">)...");

            //Set the user context
            SetContextState();

            if (string.IsNullOrEmpty(Item))
            {
                Item = "000000000000";
            }

            List<NetBay.Core.BusinessEntities.Document> documents = null;
            try
            {
                //Insert documents
                documents = DomainService.AddDocumentCoreToExistingFolder(OrganisationId, FolderTypeId, FolderId,
                                                                          DocumentsFullPath, null, Item, Note, Author,
                                                                          "", "", Rank, AddToFulltext);

                //Move documents
                RioWCFServices.WCFServiceClient L_oWCFServiceClient =
                    new RioWCFServices.WCFServiceClient("BasicHttpBinding_IWCFService");
                var l_oMessageRequest = new NetBay.Core.BusinessEntities.MessageRequest();
                l_oMessageRequest.LicenseKey = RioApplicationSettings.LicenseKey;
                l_oMessageRequest.EncryptLicense(RioApplicationSettings.LicenseKeyDuration);
                RioWCFServices.MoveOrCopyDocumentWithFullPathRequest request =
                    new RioWCFServices.MoveOrCopyDocumentWithFullPathRequest(documents, AuthenticatedUser.UserId,
                                                                             MoveDocument, l_oMessageRequest);
                L_oWCFServiceClient.MoveOrCopyDocumentWithFullPath(request);
            }
            catch (Exception ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogError("Exception in AddDocumentsToFolder : " + ex.Message);

                // set document to deleted
                if (documents != null && documents.Count > 0)
                {
                    DomainService.DeleteDocuments(documents.Select(i => i.Identifier).ToList());
                }
                return false;
            }

            return true;
        }

        /// <summary>
        /// Adds the document.
        /// </summary>
        /// <param name="OrganisationId">The organisation id.</param>
        /// <param name="FolderTypeId">The folder type id.</param>
        /// <param name="DicValorization">The dic valorization.</param>
        /// <param name="DocumentsFullPath">The documents full path.</param>
        /// <param name="Item">The item.</param>
        /// <param name="Note">The note.</param>
        /// <param name="Author">The author.</param>
        /// <param name="PhotoCredit">The photo credit.</param>
        /// <param name="VideoLenght">The video lenght.</param>
        /// <param name="AddToFulltext">if set to <c>true</c> [add to fulltext].</param>
        /// <param name="MoveDocument">The move document.</param>
        /// <param name="p_szIdCourrierErp">Courrier Id ERP</param>
        /// <param name="p_szMesureErp">Mesure ERP</param>
        /// <returns></returns>
        public bool AddDocument(long OrganisationId, long FolderTypeId, Dictionary<long, string> DicValorization,
                                List<string> DocumentsFullPath, string Item,
                                string Note, string Author, string PhotoCredit, string VideoLenght, bool AddToFulltext,
                                bool MoveDocument,
                                string p_szIdCourrierErp = "", string p_szMesureErp = "")
        {
            NetBay.Core.Log.LogManager.Instance().LogDebug("(OrganisationId<" + OrganisationId.ToString() +
                                                           "> FolderTypeId<" + FolderTypeId + "> DicValorization.count<" +
                                                           DicValorization.Count +
                                                           "> DocumentsFullPath.count<" + DocumentsFullPath.Count +
                                                           "> Item<" + Item +
                                                           "> Author<" + Author + "> Note<" + Note + "> AddToFulltext<" +
                                                           AddToFulltext.ToString() +
                                                           "> MoveDocument<" + MoveDocument.ToString() +
                                                           "> p_szIdCourrierErp<" + p_szIdCourrierErp +
                                                           "> p_szMesureErp <" + p_szMesureErp + ">)...");

            //Set the user context
            SetContextState();

            List<NetBay.Core.BusinessEntities.Document> documents = null;
            try
            {
                //Insert documents
                documents = DomainService.AddDocumentCore(OrganisationId, FolderTypeId, DicValorization,
                                                          DocumentsFullPath, null, Item, Note, Author, VideoLenght, "",
                                                          0, AddToFulltext, p_szIdCourrierErp, p_szMesureErp);

                //Move documents
                RioWCFServices.WCFServiceClient L_oWCFServiceClient =
                    new RioWCFServices.WCFServiceClient("BasicHttpBinding_IWCFService");
                var l_oMessageRequest = new NetBay.Core.BusinessEntities.MessageRequest();
                l_oMessageRequest.LicenseKey = ConfigurationManager.AppSettings.Get("LicenseKey");
                l_oMessageRequest.EncryptLicense(RioApplicationSettings.LicenseKeyDuration);
                RioWCFServices.MoveOrCopyDocumentWithFullPathRequest request =
                    new RioWCFServices.MoveOrCopyDocumentWithFullPathRequest(documents, AuthenticatedUser.UserId,
                                                                             MoveDocument, l_oMessageRequest);
                L_oWCFServiceClient.MoveOrCopyDocumentWithFullPath(request);
            }
            catch (Exception ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogError("Exception in AddDocument : " + ex.Message);

                // set document to deleted
                if (documents != null && documents.Count > 0)
                {
                    DomainService.DeleteDocuments(documents.Select(i => i.Identifier).ToList());
                }
                return false;
            }

            return true;
        }

        /// <summary>
        /// Folder exist or no
        /// </summary>
        /// <param name="p_lOrganisationId">The P_L organisation id.</param>
        /// <param name="p_lFolderTypeId">The P_L folder type id.</param>
        /// <param name="p_oIndexValorization">The p_o index valorization.</param>
        /// <returns></returns>
        public long IsFolderExist(long p_lOrganisationId, long p_lFolderTypeId,
                                  Dictionary<long, string> p_oIndexValorization)
        {
            //Set the user context
            SetContextState();

            var l_oRet = new NetBay.Core.BusinessEntities.ReturnLong();
            var l_lReturnFolderExist = new long();

            try
            {
                l_oRet = DomainService.IsFolderExist(p_lOrganisationId, p_lFolderTypeId, p_oIndexValorization);
                l_lReturnFolderExist = Convert.ToInt32(l_oRet.Value);
            }
            catch (Exception ex)
            {
                l_oRet = new NetBay.Core.BusinessEntities.ReturnLong(ex.Message);
                NetBay.Core.Log.LogManager.Instance().LogError("Exception in IsFolderExist : " + ex.Message);
            }
            return l_lReturnFolderExist;
        }

        /// <summary>
        /// Update Index Folder
        /// </summary>
        /// <param name="p_lFolderTypeId">The P_L folder type id.</param>
        /// <param name="p_lFolderId">The P_L folder id.</param>
        /// <param name="p_dicIndexValue">The p_dic index value.</param>
        /// <returns></returns>
        public bool UpdateFolderIndex(long p_lFolderTypeId, long p_lFolderId, Dictionary<string, string> p_dicIndexValue)
        {
            NetBay.Core.Log.LogManager.Instance().LogDebug("(p_lFolderTypeId<" + p_lFolderTypeId + "> p_lFolderId<" +
                                                           p_lFolderId + "> p_dicIndexValue.count<" +
                                                           p_dicIndexValue.Count + ">)...");

            //var l_oRet = new ReturnBoolean();

            try
            {
                //Update Index
                DomainService.UpdateFolderIndex(p_lFolderTypeId, p_lFolderId, p_dicIndexValue);
            }
            catch (Exception ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogError("RioService Exception in UpdateFolderIndex : " +
                                                               ex.Message);

                return false;
            }
            return true;
        }

        /// <summary>
        /// Gets the last consultations.
        /// </summary>
        /// <param name="Action">The action.</param>
        /// <param name="UserId">The user id.</param>
        /// <param name="NbLine">The nb line.</param>
        /// <param name="Search">The search.</param>
        /// <returns></returns>
        public List<NetBay.Core.BusinessEntities.Historic.HistoricInformation> GetLastConsultations(string Action,
                                                                                                    long UserId,
                                                                                                    int NbLine,
                                                                                                    bool Search)
        {
            NetBay.Core.Log.LogManager.Instance().LogDebug("(UserId<" + UserId + "> NbLine<" + NbLine + ">NbLine<" +
                                                           NbLine + ">Search<" + Search + ">)...");

            //Set the user context
            SetContextState();

            var l_oHistoricInfoResults = new List<HistoricInformation>();
            try
            {
                l_oHistoricInfoResults = DomainService.GetLastConsultations(Action, UserId, NbLine, Search);
            }
            catch (Exception ex)
            {
                var l_oHistoricInfoResult = new HistoricInformation();
                NetBay.Core.Log.LogManager.Instance().LogError("Exception in GetLastConsultations RioService : " +
                                                               ex.Message);
                l_oHistoricInfoResults.Add(l_oHistoricInfoResult);
            }
            return l_oHistoricInfoResults;
        }

        /// <summary>
        /// Return index of Orga (ERP)
        /// </summary>
        /// <param name="p_sConnectorName">Name of the P_S connector.</param>
        /// <returns></returns>
        public List<NetBay.Core.BusinessEntities.Genesis> GetGenesisFolder(string p_sConnectorName)
        {
            var returnValue = new List<NetBay.Core.BusinessEntities.Genesis>();
            try
            {
                returnValue = ErpTranslator.TranslateGenesis(DA_Erp.GetGenesisFolder(p_sConnectorName));
            }
            catch (Exception ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogError("RioService Exception in GetGenesisFolder : " +
                                                               ex.Message);
            }
            return returnValue;
        }

        /// <summary>
        /// Return Value table r_erp_param (ERP -&gt; RioWeb)
        /// </summary>
        /// <param name="p_sValue">The value.</param>
        /// <param name="p_iOrga">The orga.</param>
        /// <param name="p_iTd">The td.</param>
        /// <returns></returns>
        public string GetErpParam(string p_sValue, int p_iOrga, int p_iTd)
        {
            NetBay.Core.Log.LogManager.Instance().LogDebug("(p_sValue<" + p_sValue.ToString() + "> p_iOrga<" + p_iOrga +
                                                           "> p_iTd<" + p_iTd + ">)...");

            var l_sValueReturn = "";

            try
            {
                l_sValueReturn = ErpRepository.GetErpParam(p_sValue, p_iOrga, p_iTd);
            }
            catch (Exception Ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogError("Exception in GetErpParam RioService: " + Ex.Message);
            }

            return l_sValueReturn;
        }

        /// <summary>
        /// Gets the genesis individu exist.
        /// </summary>
        /// <param name="s_lTdTableName">Name of the S_L td table.</param>
        /// <param name="s_lIndividu">The S_L individu.</param>
        /// <param name="s_lIndexPosit">The S_L index posit.</param>
        /// <returns></returns>
        public bool GetGenesisIndividuExist(string s_lTdTableName, string s_lIndividu, string s_lIndexPosit)
        {
            NetBay.Core.Log.LogManager.Instance().LogDebug("(s_lTdTableName<" + s_lTdTableName.ToString() +
                                                           "> s_lIndividu<" + s_lIndividu.ToString() +
                                                           "> s_lIndexPosit<" + s_lIndexPosit.ToString() + ">)...");

            bool l_bIndividuExist = false;

            try
            {
                l_bIndividuExist = ErpRepository.GetGenesisIndividuExist(s_lTdTableName, s_lIndividu, s_lIndexPosit);
            }
            catch (Exception Ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogError("Exception in GetGenesisIndividuExist RioService: " +
                                                               Ex.Message);
            }

            return l_bIndividuExist;
        }

        /// <summary>
        /// Retunr courrierId
        /// </summary>
        /// <param name="s_lCourrierIdErp">The S_L courrier id erp.</param>
        /// <param name="s_lTdTableName">Name of the S_L td table.</param>
        /// <param name="s_lIndividu">The S_L individu.</param>
        /// <param name="s_lIndexPosit">The S_L index posit.</param>
        /// <returns></returns>
        public bool GetGenesisCourrierIdExist(string s_lCourrierIdErp, string s_lTdTableName, string s_lIndividu,
                                              string s_lIndexPosit)
        {
            NetBay.Core.Log.LogManager.Instance().LogDebug("(s_lCourrierIdErp<" + s_lCourrierIdErp.ToString() +
                                                           "> s_lTdTableName<" + s_lTdTableName.ToString() +
                                                           "> s_lIndividu<" + s_lIndividu.ToString() +
                                                           "> s_lIndexPosit<" + s_lIndexPosit.ToString() + ")...");

            bool l_bCourrierIdExist = false;
            try
            {
                l_bCourrierIdExist = ErpRepository.GetGenesisCourrierIdExist(s_lCourrierIdErp, s_lTdTableName,
                                                                             s_lIndividu, s_lIndexPosit);
            }
            catch (Exception Ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogError("Exception in GetGenesisCourrierIdExist RioService: " +
                                                               Ex.Message);
            }

            return l_bCourrierIdExist;
        }

        /// <summary>
        /// Return Index posit and Id
        /// </summary>
        /// <param name="s_FolderTypeTableName">Name of the s_ folder type table.</param>
        /// <returns></returns>
        public Dictionary<long, long> GetIndex(string s_FolderTypeTableName)
        {
            NetBay.Core.Log.LogManager.Instance().LogDebug("(s_FolderTypeTableName<" + s_FolderTypeTableName.ToString() +
                                                           ")...");

            Dictionary<long, long> l_dIndexRetour = new Dictionary<long, long>();
            try
            {
                l_dIndexRetour = IndexRepository.GetIndexPosition(s_FolderTypeTableName);
            }
            catch (Exception Ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogError("Exception in GetIndex RioService: " + Ex.Message);
            }
            return l_dIndexRetour;
        }

        /// <summary>
        /// Gets the name of the orga by erp.
        /// </summary>
        /// <param name="p_sConnectorName">Name of the P_S connector.</param>
        /// <returns></returns>
        public NetBay.Core.BusinessEntities.Organization GetOrgaByErpName(string p_sConnectorName)
        {
            NetBay.Core.Log.LogManager.Instance().LogDebug("(p_sConnectorName<" + p_sConnectorName + ")...");

            var l_lstErpConnByName = new NetBay.Core.BusinessEntities.Organization();

            try
            {
                l_lstErpConnByName = ErpRepository.GetOrgaByErpName(p_sConnectorName);
            }
            catch (Exception Ex)
            {
                NetBay.Core.Log.LogManager.Instance().LogError("Exception in GetOrgaByErpName RioService: " + Ex.Message);
            }
            return l_lstErpConnByName;
        }

        /// <summary>
        /// Performs the NTLM authentication.
        /// </summary>
        /// <returns></returns>
        public bool PerformNTLMAuthentication()
        {
            string UserName = HttpContext.Current.User.Identity.Name;
            if (UserName.Contains("\\"))
            {
                UserName = UserName.Substring(UserName.IndexOf(@"\") + 1, UserName.Length - UserName.IndexOf(@"\") - 1);
            }

            AuthenticatedUser = DomainService.GetAccess(UserName, "", 0).ToList().FirstOrDefault();
            if (AuthenticatedUser != null)
                return true;
            else
                return false;
        }

        /// <summary>
        /// Performs the rio authentication.
        /// </summary>
        /// <param name="UserName">Name of the user.</param>
        /// <param name="Password">The password.</param>
        /// <returns></returns>
        public bool PerformRioAuthentication(string UserName, string Password)
        {
            AuthenticatedUser = DomainService.GetAccess(UserName, Password, 1, false).ToList().FirstOrDefault();
            if (AuthenticatedUser != null)
                return true;
            else
                return false;
        }

        /// <summary>
        /// Gets all users.
        /// </summary>
        /// <returns></returns>
        public List<NetBay.Core.BusinessEntities.User> GetAllUsers()
        {
            return Rio.Doc.Business.Repository.UserRepository.FindAllUser();
        }

        #endregion
    }
}